package top.infopub.mgr.sg.web;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.cache.RedisCached;
import top.infopub.generic.GenericController;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.sg.service.DeskNoticeService;
import top.infopub.mgr.sg.vo.DeskNoticeVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.sg.DeskNotice;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.util.GrpParaUtil;

import com.github.pagehelper.Page;


/**
 * 公告管理
 * @author wangw
 * @version 2019年12月31日
 * @see NoticeController
 * @since
 */
@Controller
@RequestMapping("/notice")
public class NoticeController extends GenericController {

    @Autowired
    private DeskNoticeService deskNoticeService;

    @Autowired
    private RedisCached redisCached;

    /**
     * 公告列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "sg/lay-notice-list";
    }
    
    /**
     * 公告列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<DeskNoticeVo> queryDataByCondition(DeskNoticeVo deskNoticeVo, ParamPage paramPage) {
        Page<DeskNoticeVo> page = new Page<DeskNoticeVo>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (deskNoticeVo.getEndDate() != null) {
            deskNoticeVo.setEndDate(DateUtils.addDays(deskNoticeVo.getEndDate(), 1));
        }
        page = deskNoticeService.selectPageByDomainWhere(page, deskNoticeVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 首页工作台-公告阅读记录
     * @return
     */
    @RequestMapping("/queryData")
    @ResponseBody
    public RspVo<DeskNoticeVo> queryData(DeskNoticeVo deskNoticeVo, ParamPage paramPage) {
        Page<DeskNoticeVo> page = new Page<DeskNoticeVo>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (deskNoticeVo.getEndDate() != null) {
            deskNoticeVo.setEndDate(DateUtils.addDays(deskNoticeVo.getEndDate(), 1));
        }
        deskNoticeVo.setState(1);//启用中
        page = deskNoticeService.selectHomePageByDomainWhere(page, deskNoticeVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 首页工作台-根据id查询公告详情
     * @param id 公告Id
     * @return 
     * @see
     */
    @RequestMapping("/queryById")
    public @ResponseBody ModelAndView queryById(HttpServletRequest request){
        String id = request.getParameter("id");
        Map<String, Object> map = new HashMap<String, Object>();
        DeskNotice deskNotice = deskNoticeService.selectByPrimaryKey(id);
        map.put("deskNotice", deskNotice);
        /**
         * 设置redis缓存为已读
         */
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String key = deskNotice.getId();
        String member = vo.getId();
        if(!redisCached.sismember(key, member)){//判断用户是否已读
            redisCached.sadd(key, member);
        }
        return new ModelAndView("sg/lay-notice-detail", map);
    }
    
    /**
     * 新增/编辑公告
     * @param deskNotice
     * @return 
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/save")
    public @ResponseBody RspVo<DeskNotice> save(DeskNotice deskNotice) {
        if (StringUtils.isEmpty(deskNotice.getTitle()) 
            || StringUtils.isEmpty(deskNotice.getTypes())
            || StringUtils.isEmpty(deskNotice.getSummary())
            || StringUtils.isEmpty(deskNotice.getContent())
            || deskNotice.getIsTop() == null){
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        deskNoticeService.saveNotice(deskNotice);
        if(StringUtils.isEmpty(deskNotice.getId())){
            LogUtil.bizLog(LogModelType.OTHER, AcctionType.ADD, "新增公告 - 标题:" + deskNotice.getTitle().trim() + "; 摘要:" + deskNotice.getSummary().trim(), null);
        }else{
            LogUtil.bizLog(LogModelType.OTHER, AcctionType.UPDATE, "修改公告 - 公告Id:" + deskNotice.getId(), null);
        }
        return RspVo.getSuccessResponse(deskNotice);
    }
    
    /**
     * 首页-公告修改为全部已读状态
     * @param operatorVo
     * @return 
     * @see
     */
    @RequestMapping("/updateReadStatus")
    public @ResponseBody RspVo<String> updateReadStatus() {
        DeskNotice deskNotice = new DeskNotice();
        deskNotice.setState(1);//启用中
        List<DeskNotice> notices = deskNoticeService.selectByEntityWhere(deskNotice);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        for(DeskNotice notice : notices){
            String key = notice.getId();
            String member = vo.getId();
            redisCached.sadd(key, member);
        }
        // 操作日志
        LogUtil.bizLog(
            LogUtil.LogModelType.OTHER,
            LogUtil.AcctionType.UPDATE,
            "首页-公告设为全部已读状态", "");
        return RspVo.getSuccessResponse();
    }
    /**
     * 修改公告状态
     * @param operatorVo
     * @return 
     * @see
     */
    @RequestMapping("/updateStatus")
    public @ResponseBody RspVo<String> updateStatus(DeskNotice deskNotice) {
        DeskNotice notice = deskNoticeService.selectByPrimaryKey(deskNotice.getId());
        Integer oldStatus = notice.getState();
        Integer newStatus = 0;
        if(oldStatus == 0){
            newStatus = 1;
        }else{
            newStatus = 0;
        }
        notice.setState(newStatus);
        notice.setUptTime(new Date());
        notice.setUptBy(SessionUserUtils.getSessionUserName());
        deskNoticeService.updateBySelective(notice);
        // 操作日志
        LogUtil.bizLog(
            LogUtil.LogModelType.OTHER,
            LogUtil.AcctionType.UPDATE,
            "修改状态  公告标题:" + notice.getTitle() + " 原状态:"
                + GrpParaUtil.getName("A00010020", String.valueOf(oldStatus)) + " 被修改为:"
                + GrpParaUtil.getName("A00010020", String.valueOf(newStatus)), "");
        return RspVo.getSuccessResponse();
    }

    /**
     * 上传公告附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadFile")
    public @ResponseBody RspVo uploadFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
        Map<String, Object> retMap = new HashMap<String, Object>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 服务器资源路径
                String serverPath = "deskNotice";
                String filePath = FileHelper.upload(file, serverPath);
                retMap.put("src",  request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+filePath);
                retMap.put("title", file.getOriginalFilename().trim());
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传公告附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(retMap);
    }
}
